//
//  XLLLoginViewModel.m
//  XLLogin
//
//  Created by 陈宪栋 on 2017/11/15.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "XLLLoginViewModel.h"
#import "XLHTTPSessionManager+Login.h"
//#import "XLLLoginManager.h"
//#import "XLLAPIManager.h"

@interface XLLLoginViewModel ()
//获取验证码按钮enable信号
@property (nonatomic, strong, readonly) RACSignal *enableCodeBtnSignal;
//完成按钮enable信号
@property (nonatomic, strong, readonly) RACSignal *enableLoginBtnSignal;
@property (nonatomic, strong, readonly) RACSignal *enableBindBtnSignal;
//定时器
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) id data;
@end

@implementation XLLLoginViewModel
- (instancetype)init {
    self = [super init];
    if (self) {
        [self initEnableSignal];
        [self initBind];
    }
    return self;
}

- (void)dealloc {
    NSLog(@"dealloc %@", [self class]);
}

- (void)initEnableSignal {
    _intervalTimeSignal = RACObserve(self, intervalTime);
    
    _enablePhoneFieldSignal = [RACObserve(self, phone) map:^id(NSString *phone) {
        return @(phone.length == 11);
    }];
    _enableCodeFieldSignal = [RACObserve(self, code) map:^id(NSString *code) {
        return @(code.length > 0);
    }];
    _enableCodeBtnSignal = [RACSignal combineLatest:@[_enablePhoneFieldSignal, _intervalTimeSignal] reduce:^id(NSNumber *value1,NSNumber *value2){
        NSLog(@"value1 = %@, value2 = %@", value1, value2);
        return @([value1 boolValue] && [value2 integerValue] == 0);
    }];
    _enableBindBtnSignal = [RACSignal combineLatest:@[_enablePhoneFieldSignal, _enableCodeFieldSignal] reduce:^id(NSNumber *value1,NSNumber *value2){
        return @([value1 boolValue] && [value2 boolValue]);
    }];
    _enableLoginBtnSignal = [RACSignal combineLatest:@[_enablePhoneFieldSignal, _enableCodeFieldSignal] reduce:^id(NSNumber *value1,NSNumber *value2){
        return @([value1 boolValue] && [value2 boolValue]);
    }];
    
}

- (void)initBind {
    [self.enableCodeBtnSignal subscribeNext:^(id x) {
        NSLog(@"enableCodeBtnSignal = %@", x);
    }];
    @weakify(self);
    _queryCodeCommand = [[RACCommand alloc] initWithEnabled:self.enableCodeBtnSignal signalBlock:^RACSignal *(id input) {
        @strongify(self);
        return [self requestCheckcodeSignal];
    }];
    
    _loginCommand = [[RACCommand alloc] initWithEnabled:self.enableLoginBtnSignal signalBlock:^RACSignal *(id input) {
        @strongify(self);
        return [self requestLoginSignal];
    }];
    _bindCommand = [[RACCommand alloc] initWithEnabled:self.enableBindBtnSignal signalBlock:^RACSignal *(id input) {
        @strongify(self);
        return [self requestBindSignal];
    }];
    //获取验证码成功
    [_queryCodeCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        self.queryCodeStatus = XLLLoginViewModelStatus_Success;
        [self startTime];
    }];
    
    
    
    //获取验证码失败
    [_queryCodeCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        self.queryCodeError = x;
        self.queryCodeStatus = XLLLoginViewModelStatus_Fail;
    }];
    //正在获取验证码
    [[_queryCodeCommand.executing skip:1] subscribeNext:^(id x) {
        @strongify(self);
        BOOL result = [x boolValue];
        if (result) {
            self.queryCodeStatus = XLLLoginViewModelStatus_Doing;
        }
    }];
    //绑定失败
    [_bindCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        self.BindError = x;
        self.BindStatus = XLLLoginViewModelStatus_Fail;
    }];
    //绑定成功
    [_bindCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        self.data = x;
        self.BindStatus = XLLLoginViewModelStatus_Success;
    }];
    //登录成功
    [_loginCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        self.data = x;
        XLUserInfoModel *model = x;
        [UserDefaults setObject:model.Id forKey:UserID];
        [UserDefaults setObject:model.HeadImg forKey:UserHead];
        [UserDefaults setObject:model.NickName forKey:UserNick];
        [UserDefaults setObject:model.Token forKey:UserToken];
//        [UserDefaults setObject:@"no" forKey:@"isYoukeInfor"];
        [UserDefaults synchronize];
        [XLHTTPSessionManager attemptDealloc];

        [[XLAccountManager shareInstance] updateUserInfo:model];
        self.loginStatus = XLLLoginViewModelStatus_Success;
    }];
    
    //登录失败
    [_loginCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        self.loginError = x;
        self.loginStatus = XLLLoginViewModelStatus_Fail;
    }];
    
    // 登录中
    [[_loginCommand.executing skip:1] subscribeNext:^(id x) {
        @strongify(self);
        BOOL result = [x boolValue];
        if (result) {
            self.loginStatus = XLLLoginViewModelStatus_Doing;
        }
    }];
}

- (void)startTime{
    self.intervalTime = self.intervalTime > 0 ? self.intervalTime : 60;
    self.intervalTime -- ;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(redoHandle) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)stopTime {
    if (self.timer) {
        self.intervalTime = 0;
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)redoHandle {
    self.intervalTime --;
    if (self.intervalTime <= 0) {
        [self stopTime];
    }
}

- (RACSignal *)requestCheckcodeSignal {
    return [[XLHTTPSessionManager sharedManager] getCodeWithPhone:self.phone];
}

- (RACSignal *)requestLoginSignal {
    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
    return [manager userLoginWithPhone:self.phone code:self.code];
}
- (RACSignal *)requestBindSignal {
    
    return [[XLHTTPSessionManager sharedManager] userBindWithPhone:self.phone code:self.code];
}
@end
